{% extends 'base.html' %}
{% load staticfiles %}

{% block link_css %}
    <style>
        .log-ul {
            width: auto;
            height: 550px;
            overflow: scroll;
            padding: 8px;
            margin: 8px;
        }

        textarea {
            width: 850px;
            border: 1px solid #eee;
            height: 300px;
            color: #999;
        }
    </style>
{% endblock %}

{% block right_content %}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-info">
                <div class="box-header">
                    <div class="mailbox-read-info">
                        <h3 class="box-title"><i class="fa fa-cog"></i> SQL执行任务--> 执行</h3>
                        <h3 id="taskid" style="display: none">{{ taskid }}</h3>
                    </div>
                </div>
                <div class="box-body">
                    <div id="toolbar">
                        <div class="form-inline" role="form">
                            <button type="button"
                                    class="btn btn-primary" onclick="start_full_execute()"><i
                                    class="fa fa-hand-pointer-o"></i>
                                全部执行
                            </button>
                            <button type="button"
                                    class="btn btn-primary" onclick="preview_sql()"><i
                                    class="fa fa-eye"></i>
                                SQL预览
                            </button>
                        </div>
                    </div>
                    <table id="demo-table"></table>
                </div>
            </div>
        </div>
    </div>

    <div class="box-size" id="typediv1" style="visibility: hidden">
        <div class="box">
            <div class="box-header">
                <div class="mailbox-read-info">
                    <h3 class="box-title"><i class="fa fa-hand-o-right"></i> 输出</h3>
                </div>
            </div>

            <div class="box-body no-padding">
                <dl id="output_append" class="log-ul">
                </dl>
            </div>
        </div>
    </div>

    <!-- 执行结果模态框 -->
    <div class="modal fade modal-wide" id="rollbackupModal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"><i class="fa fa-hand-o-right"></i> 执行结果</h4>
                </div>
                <div class="modal-body">
                    <div class="box">
                        <div class="box-body box-comments">
                            <div class="box-comment">
                                <h5><i class="fa fa-tag"> 回滚SQL</i></h5>
                                <textarea title="" style="resize: none" readonly="readonly" id="select_sql"></textarea>
                            </div>
                            <div class="box-comment">
                                <h5><i class="fa  fa-info-circle"> 执行日志</i></h5>
                                <hr>
                                <dl id="execLog">
                                </dl>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- SQL预览模态框 -->
    <div class="modal fade" id="modal_preview_sql" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel"><i class="fa fa-eye"></i> SQL预览
                    </h4>
                </div>

                <div class="modal-body">
                    <div class="row">
                        <div class="box-body">
                            <textarea title="" id="preview_sql_contents"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block link_javascripts %}
    <script src="{% static 'c_websocket.js' %}"></script>

    <script>
        /**
         * 初始化bootstrap-table，生成表格
         */
        let taskid = '\'' + $('#taskid').text() + '\'';
        $(function () {
            $('#demo-table').bootstrapTable({
                method: 'get',
                dataType: 'json',
                url: "{% url 'p_perform_tasks_details' %}",
                queryParams: function queryParams() {
                    return {'taskid': taskid.toString()};
                },
                cache: true,
                sidePagination: "client",
                showColumns: true,
                pagination: true,
                search: true,
                showRefresh: true,
                singleSelect: true,
                toolbar: '#toolbar',
                minimumCountColumns: 2,
                pageNumber: 1,
                pageSize: 20,
                pageList: [10, 20, 30],
                uniqueId: "id",
                fixedColumns: true,
                fixedNumber: +1,
                classes: 'table table-hover table-no-bordered',

                columns: [
                    {
                        field: 'sid',
                        title: 'ID',
                        sortable: true
                    },
                    {
                        field: 'user',
                        title: '用户',
                        sortable: true
                    }, {
                        field: 'sql',
                        title: 'sql语句',
                        sortable: true,
                        formatter: function (value) {
                            if (value.length >= 128) {
                                return '<a href="#" data-toggle="tooltip" title=\"' + value + '\">' + value.slice(0, 128) + '&nbsp;...' + '</a>'
                            }
                            else {
                                return '<a href="#" data-toggle="tooltip" title=\"' + value + '\">' + value + '</a>'
                            }
                        }
                    },
                    {
                        field: 'sqlsha1',
                        title: 'sqlsha1',
                        sortable: true
                    },
                    {
                        field: 'exec_status',
                        title: '任务进度',
                        formatter: function (value, row, index) {
                            if (value === '已完成') {
                                return "<p class='text-green'>" + value + "</p>"
                            }
                            else if (value === '已回滚') {
                                return "<p class='text-blue'>" + value + "</p>"
                            }
                            else if (value === '处理中') {
                                return "<p class='text-yellow'>" + value + "</p>"
                            }
                            else if (value === '回滚中') {
                                return "<p class='text-yellow'>" + value + "</p>"
                            }
                            else if (value === '未执行') {
                                return "<p class='text-red'>" + value + "</p>"
                            }
                            else if (value === '失败') {
                                return "<p class='text-red'>" + value + "</p>"
                            }
                            else if (value === '异常') {
                                return "<p class='text-red'>" + value + "</p>"
                            }
                        }
                    },
                    {
                        field: 'id',
                        title: "执行",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="execSingleTasks(' + row.id + ')"><i class="fa fa-play"></i></a> ';
                        }
                    },

                    {
                        field: 'id',
                        title: "暂停(gh-ost)",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="PerformTasksStop(' + row.id + ', \'pause_ghost\')"><i class="fa fa-pause"></i></a> ';
                        }
                    },
                    {
                        field: 'id',
                        title: "恢复(gh-ost)",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="PerformTasksStop(' + row.id + ', \'recovery_ghost\')"><i class="fa fa-play"></i></a> ';
                        }
                    },
                    {
                        field: 'id',
                        title: "终止(gh-ost)",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="PerformTasksStop(' + row.id + ', \'stop_ghost\')"><i class="fa fa-power-off"></i></a> ';
                        }
                    },
                    {
                        field: 'id',
                        title: "终止(pt-osc)",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="PerformTasksStop(' + row.id + ', \'stop_ptosc\')"><i class="fa fa-power-off"></i></a> ';
                        }
                    },
                    {
                        field: 'id',
                        title: "回滚",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="PerformTasksRollback(' + row.id + ')"><i class="fa fa-undo"></i></a> ';
                        }
                    },
                    {
                        field: 'id',
                        title: "结果",
                        formatter: function (value, row) {
                            return '<a href="#" onclick="getPerformTasksResult(' + row.id + ')"><i class="fa fa-list-ol"></i></a> ';
                        }
                    }
                ]
            })
        });

        /**
         * 每3s刷新一次表格
         */

        $(function () {
            function refreshTable() {
                $('#demo-table').bootstrapTable('refresh', {silent: true});
            }

            setInterval(refreshTable, 3000);
        });

        <!-- 获取回滚语句和执行结果日志 -->
        function getPerformTasksResult(id) {
            let select_sql = $('#select_sql');
            let exec_log = $('#execLog');
            $.ajax({
                url: "{% url 'p_get_perform_tasks_result' %}",
                type: 'GET',
                dataType: 'json',
                data: {'id': id},
                timeout: 10000,
                cache: false,
                success: function (result) {
                    select_sql.empty();
                    exec_log.empty();
                    if (result.status === 0) {
                        let log_html = renderIncepExecResult(result.data.exec_log);
                        let rollback_sql = '';
                        if (result.data.rollback_log) {
                            rollback_sql = result.data.rollback_log
                        }
                        else {
                            rollback_sql = ' 无记录'
                        }
                        select_sql.append(rollback_sql);
                        exec_log.append(log_html);
                        $('#rollbackupModal').modal('show');
                    } else if (result.status === 1) {
                        exec_log.append(result.data.exec_log.replace(/\n/g, '\.' + '<br>'));
                        $('#rollbackupModal').modal('show');
                    } else if (result.status === 2) {
                        displayPNotify(result.status, result.msg)
                    }
                }
            })
        }

        <!-- 全部执行 -->
        function start_full_execute() {
            let csrftoken = $.cookie('csrftoken');

            $.ajax({
                url: "{% url 'p_full_perform_tasks' %}",
                type: 'POST',
                dataType: 'json',
                data: {
                    'taskid': taskid,
                    'csrfmiddlewaretoken': csrftoken
                },
                timeout: 10000,
                cache: false,
                success: function (result) {
                    displayPNotify(result.status, result.msg);
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        displayPNotify(jqXHR.status)
                    }
                }
            })
        }

        <!-- 执行 -->
        function execSingleTasks(id) {
            let csrftoken = $.cookie('csrftoken');

            $.ajax({
                url: "{% url 'p_single_perform_tasks' %}",
                type: 'POST',
                dataType: 'json',
                data: {
                    'id': id,
                    'taskid': taskid,
                    'csrfmiddlewaretoken': csrftoken
                },
                timeout: 10000,
                cache: false,
                success: function (result) {
                    displayPNotify(result.status, result.msg);
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        displayPNotify(jqXHR.status)
                    }
                }
            })
        }

        <!-- 停止 -->
        function PerformTasksStop(id, action) {
            let csrftoken = $.cookie('csrftoken');

            $.ajax({
                url: "{% url 'p_perform_tasks_stop' %}",
                type: 'POST',
                dataType: 'json',
                data: {
                    'id': id,
                    'action': action,
                    'taskid': taskid,
                    'csrfmiddlewaretoken': csrftoken
                },
                timeout: 10000,
                cache: false,
                success: function (result) {
                    displayPNotify(result.status, result.msg);
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        displayPNotify(jqXHR.status)
                    }
                }
            })
        }

        <!-- 回滚 -->
        function PerformTasksRollback(id) {
            let csrftoken = $.cookie('csrftoken');

            $.ajax({
                url: "{% url 'p_perform_tasks_rollback' %}",
                type: 'POST',
                dataType: 'json',
                data: {
                    'id': id,
                    'taskid': taskid,
                    'csrfmiddlewaretoken': csrftoken
                },
                timeout: 10000,
                cache: false,
                success: function (result) {
                    displayPNotify(result.status, result.msg);
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        displayPNotify(jqXHR.status)
                    }
                }
            })
        }

        <!-- 预览SQL -->
        let myTextarea = document.getElementById('preview_sql_contents');
        let myCodeMirror = CodeMirror.fromTextArea(myTextarea, {
            mode: "text/x-mysql",
            autoRefresh: true,
            readOnly: true,
            theme: 'material'
        });

        function preview_sql() {
            $('#preview_sql_contents').empty();
            $.ajax({
                url: "{% url 'p_perform_tasks_sqlpre' %}",
                type: 'GET',
                dataType: 'json',
                data: {
                    'taskid': taskid
                },
                timeout: 10000,
                cache: false,
                success: function (result) {
                    let data = result.join(';\n\n');
                    myCodeMirror.setValue(data);
                    $('#modal_preview_sql').modal('show')
                },
                error: function (jqXHR) {
                    if (jqXHR.status === 403) {
                        displayPNotify(jqXHR.status)
                    }
                }
            })
        }

        <!-- 创建websocket，获取执行进度 -->
        $(document).ready(function () {
            CreateWebSocket();
        });

    </script>
{% endblock %}